package com.ddm.controller.common;


import com.ddm.context.BaseContext;
import com.ddm.exception.DataErrorException;
import com.ddm.properties.UploadImageProperties;
import com.ddm.service.webService.WebUserService;
import com.ddm.utils.DownloadFileUtil;
import com.ddm.utils.UploadImageUtil;
import com.ddm.constant.MessageConstant;
import com.ddm.result.Result;
import com.ddm.utils.UploadVideoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author 丁丁猫
 * @version 1.0
 */
@RestController("CommonFileController")
@RequestMapping("/common")
@Api(tags = "文件相关接口")
@Slf4j
public class FileController {
    @Autowired
    DownloadFileUtil downloadFileUtil;
    @Autowired
    UploadVideoUtil uploadVideoUtil;
    @Autowired
    UploadImageUtil uploadImageUtil;
    @Autowired
    UploadImageProperties uploadImageProperties;
    @Autowired
    private WebUserService userService;
    /**
     * 图片上传到resource路径下 upload文件中
     * @param file
     * @return
     * @throws IOException
     */

    @PostMapping("/image")
    @ApiOperation("图片上传")
    public Result<String> uploadImage(MultipartFile file){
        if (file.isEmpty())
            return Result.error(MessageConstant.NULL_DATA);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID() + extension;
            String filePath = uploadImageUtil.sshSftp(file.getBytes(), objectName);
            return Result.success(filePath);

        } catch (Exception e) {
            log.error("文件上传失败:{}",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
    /**
     * 从云存储下载文件并返回客户端
     * @param fileName 要下载的文件名
     * @return 下载的文件流
     */
    @GetMapping("/downloadFile")
    @ApiOperation("文件下载")
    public ResponseEntity<byte[]> downloadFile(@RequestParam String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        try {
            // 本地临时文件临时路径（可根据实际情况调整）
            String localTempPath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

            // 调用工具类从云存储下载文件到本地临时目录
            String localFilePath = downloadFileUtil.sshSftpDownload(fileName, localTempPath);

            // 读取本地文件为字节数组
            File file = new File(localFilePath);
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            fis.read(bytes);
            fis.close();

            // 设置响应头，支持中文文件名
            HttpHeaders headers = new HttpHeaders();
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
            headers.setContentDispositionFormData("attachment", encodedFileName);
            headers.setContentLength(file.length());

            // 删除临时文件
            file.delete();

            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);

        } catch (Exception e) {
            log.error("文件下载失败:{}", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    /**
     * 视频上传到resource路径下 upload文件中
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/video")
    @ApiOperation("视频上传")
    public Result<String> uploadVideo(MultipartFile file){
        if (file.isEmpty())
            return Result.error(MessageConstant.NULL_DATA);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID() + extension;
            String filePath = uploadVideoUtil.sshSftp(file.getBytes(), objectName);
            return Result.success(filePath);

        } catch (Exception e) {
            log.error("文件上传失败:{}",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
    /**
     * 多图片上传到resource路径下 upload文件中
     * @param files 文件列表
     * @return 所有文件的路径列表
     * @throws IOException
     */
    @PostMapping("/images")
    @ApiOperation("多图片上传")
    public Result<List<String>> uploadImages(@RequestParam("files") List<MultipartFile> files) {
        // 检查文件列表是否为空
        if (files == null || files.isEmpty()) {
            return Result.error(MessageConstant.NULL_DATA);
        }

        List<String> filePaths = new ArrayList<>();

        try {
            for (MultipartFile file : files) {
                // 跳过空文件
                if (file.isEmpty()) {
                    continue;
                }

                // 原始文件名
                String originalFilename = file.getOriginalFilename();
                // 截取文件后缀
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                // 生成唯一文件名
                String objectName = UUID.randomUUID() + extension;
                // 上传文件并获取路径
                String filePath = uploadImageUtil.sshSftp(file.getBytes(), objectName);
                // 添加到结果列表
                filePaths.add(filePath);
            }

            // 检查是否有成功上传的文件
            if (filePaths.isEmpty()) {
                return Result.error(MessageConstant.UPLOAD_FAILED);
            }

            return Result.success(filePaths);

        } catch (Exception e) {
            log.error("文件上传失败:{}", e);
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
    /**
     * 从云存储下载文件并返回客户端（基于用户ID的权限校验）
     * @param fileName 要下载的文件名
     * @param reportType 文档类型：0-普通文档，1-VIP文档
     * @return 下载的文件流
     */
    @GetMapping("/downloadMAFile")
    @ApiOperation("市场报告文件下载（带权限控制）")
    public ResponseEntity<byte[]> downloadFile(
            @RequestParam String fileName,
            @RequestParam @ApiParam(value = "文档类型：0-普通文档，1-VIP文档", required = true) Integer reportType) {

        // 参数校验
        if (fileName == null || fileName.isEmpty() || reportType == null || (reportType != 0 && reportType != 1)) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        try {
            // 1. 从BaseContext获取当前登录用户ID（拦截器中已设置）

            Long userId = BaseContext.getCurrentId();
            log.info("当前下载文件用户ID: {}", userId);
            if (userId == null) {
                // 用户未登录
                return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);


            }

            // 2. 根据用户ID查询用户类型（需注入用户服务）
            Integer userType = userService.getUserTypeById(userId);
            if (userType == null) {
                // 用户不存在
//                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
               throw new DataErrorException("用户不存在");
            }

            // 3. 权限判断逻辑
            // 普通用户（0）：不能下载任何文档
            if (userType == 0) {
//                return new ResponseEntity<>(HttpStatus.FORBIDDEN);
                throw new DataErrorException("普通用户不能下载任何文档");
            }


            // VIP文档(1)：仅管理员(1)和VIP用户(3)可下载
            if (reportType == 1) {
                if (!(userType == 1 || userType == 3)) {
                   throw new DataErrorException("普通用户不能下载VIP文档");

                }
            }
//            // 普通文档（0）：收费用户（2）、管理员（1）、VIP用户（3）可下载
//            if (reportType == 0 && !(userType == 1 || userType == 2 || userType == 3)) {
//                return new ResponseEntity<>(HttpStatus.FORBIDDEN);
//            }

            // 4. 权限通过，执行下载逻辑
            String localTempPath = System.getProperty("java.io.tmpdir") + File.separator + fileName;
            String localFilePath = downloadFileUtil.sshSftpDownload(fileName, localTempPath);

            File file = new File(localFilePath);
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            fis.read(bytes);
            fis.close();

            // 设置响应头，支持中文文件名
            HttpHeaders headers = new HttpHeaders();
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
            headers.setContentDispositionFormData("attachment", encodedFileName);
            headers.setContentLength(file.length());

            // 删除临时文件
            file.delete();

            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);

        } catch (Exception e) {
            log.error("文件下载失败:{}", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
